package com.homedo.odin.solution.service;

import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.base.service.BaseService;
import com.homedo.core.common.exception.BizException;
import com.homedo.odin.solution.contract.mng.response.column.ColumnSkuListResponseBean;
import com.homedo.odin.solution.dao.ColumnSkuMapper;
import com.homedo.odin.solution.dao.SpecialColumnMapper;
import com.homedo.odin.solution.enumcode.basic.DeleteEnum;
import com.homedo.odin.solution.model.dto.SkuBean;
import com.homedo.odin.solution.model.entity.ColumnSku;
import com.homedo.odin.solution.model.entity.SpecialColumn;
import com.homedo.odin.solution.model.request.mng.column.AddColumnRelevanceSkuRequestBean;
import com.homedo.odin.solution.model.request.mng.column.ColumnSkuRequestBean;
import com.homedo.odin.solution.model.request.mng.column.RemoveColumnRelevanceSkuRequestBean;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p> 栏目关联sku关系表 服务实现类 </p>
 *
 * @author HarveyDing
 * @since 2018-03-08
 */
@Service
public class ColumnSkuServiceImpl extends BaseService<ColumnSkuMapper, ColumnSku> {

    @Autowired
    private ColumnSkuMapper columnSkuMapper;
    @Autowired
    private SpecialColumnMapper specialColumnMapper;

    /*****************张磊Start******************/


    /**
     * OMS_新增栏目关联sku
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchAddColumnSku(AddColumnRelevanceSkuRequestBean requestBean) {
        SpecialColumn specialColumn = specialColumnMapper.getSpecialColumn(requestBean.getColumnId());
        if (specialColumn == null) {
            throw new BizException(Meta.CODE_451.getCode(), "该栏目不存在");
        }

        Long columnId = requestBean.getColumnId();
        List<ColumnSkuRequestBean> columnSkuList = requestBean.getColumnSkuList();
        List<ColumnSku> skuList = columnSkuList.stream().map(columnSkuBean -> {
            ColumnSku sku = new ColumnSku();
            sku.setSkuId(columnSkuBean.getSkuId());
            sku.setSkuName(columnSkuBean.getSkuName());
            sku.setCreateUserName(requestBean.getUserName());
            sku.setColumnId(columnId);
            sku.setStatus(columnSkuBean.getStatus());
            return sku;
        }).collect(Collectors.toList());

        //栏目是否有绑定sku
        Set<String> skuIds = skuList.stream().map(sku -> sku.getSkuId()).collect(Collectors.toSet());
        List<ColumnSku> dbSkuList = columnSkuMapper.selectBySkuIdsAndColumnId(skuIds, columnId);

        if (CollectionUtils.isNotEmpty(dbSkuList)) {
            Map<Integer, List<ColumnSku>> groupSkuMap = dbSkuList.stream()
                    .collect(Collectors.groupingBy(sku -> sku.getIsDel()));
            List<ColumnSku> isDelSkuList = groupSkuMap.get(DeleteEnum.IS_DEL.getDbValue());
            Set<String> notExist = new HashSet<>();

            if (CollectionUtils.isNotEmpty(isDelSkuList)) {
                //已删除的修改 状态成 未删除
                Set<String> skuIdList = isDelSkuList.stream().map(sku -> sku.getSkuId()).collect(Collectors.toSet());
                columnSkuMapper.updateIsDelBySkuIdsAndColumnId(DeleteEnum.NOT_DEL.getDbValue(), skuIdList, columnId);
                notExist.addAll(skuIdList);
            }

            //未删除修改操作人  时间等
            List<ColumnSku> notDelSkuList = groupSkuMap.get(DeleteEnum.NOT_DEL.getDbValue());
            if (CollectionUtils.isNotEmpty(notDelSkuList)) {
            }

            notDelSkuList.forEach(bean -> {
                Date date = new Date();
                bean.setCreateUserName(requestBean.getUserName());
                bean.setLastModifiedTime(date);
                bean.setCreateTime(date);
                columnSkuMapper.updateById(bean);
            });
            Set<String> skuIdList = notDelSkuList.stream().map(sku -> sku.getSkuId()).collect(Collectors.toSet());
            notExist.addAll(skuIdList);

            //筛选出 提交的商品列表中在数据库中不存在的做新增操作
            List<ColumnSku> insertList = skuList.stream().filter(sku -> !notExist.contains(sku.getSkuId().toString()))
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(insertList)) {
                columnSkuMapper.insertBatch(insertList);
            }

            return;
        }
        //没有数据新增操作
        columnSkuMapper.insertBatch(skuList);
    }


    /**
     * OMS_移除栏目关联sku
     */
    @Transactional(rollbackFor = Exception.class)
    public void delColumnSku(RemoveColumnRelevanceSkuRequestBean requestBean) {
        Long columnId = requestBean.getColumnId();
        List<ColumnSkuRequestBean> skus = requestBean.getSkus();
        Set<String> skuIds = skus.stream().map(bean -> bean.getSkuId().toString()).collect(Collectors.toSet());

        List<ColumnSku> dbSkuList = columnSkuMapper.selectBySkuIdsAndColumnId(skuIds, columnId);
        if (CollectionUtils.isEmpty(dbSkuList)) {
            throw new BizException(Meta.CODE_451.getCode(), "删除失败,该栏目下没有SKU数据");
        }

        //全部找到 执行删除
        if (dbSkuList.size() == skuIds.size()) {
            columnSkuMapper.updateIsDelBySkuIdsAndColumnId(DeleteEnum.IS_DEL.getDbValue(), skuIds, columnId);
        } else {
            //部分未找到，需要提示未删除成功的数据
            Set<String> existIds = dbSkuList.stream().map(sku -> sku.getSkuId()).collect(Collectors.toSet());
            //删除以存在的
            columnSkuMapper.updateIsDelBySkuIdsAndColumnId(DeleteEnum.IS_DEL.getDbValue(), existIds, columnId);
        }
    }


    /**
     * 根据栏目id查询sku列表
     */
    public ColumnSkuListResponseBean getSkuListByColumnId(Long columnId, int delStatus) {
        List<ColumnSku> columnSkuList = columnSkuMapper.getSkuListByColumnId(columnId, delStatus);
        List<SkuBean> skuList = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(columnSkuList)) {
            columnSkuList.forEach(columnSku -> {
                //组装Bean
                SkuBean skuBean = new SkuBean();
                skuBean.setSkuId(columnSku.getSkuId());
                skuBean.setSkuName(columnSku.getSkuName());
                skuBean.setStatus(columnSku.getStatus());
                skuList.add(skuBean);
            });
        }

        ColumnSkuListResponseBean responseBean = new ColumnSkuListResponseBean();
        responseBean.setColumnId(columnId);
        responseBean.setSkuList(skuList);
        return responseBean;
    }

    /*****************张磊End******************/
}
